package common

import (
	"github.com/gogf/gf/v2/os/gcfg"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/text/gstr"
)

type BakupItem struct {
	Source string `json:"source"`
	To     string `json:"to"`
}

func backupSync() {
	ctx := gctx.New()
	c := gcfg.Instance()
	if c.Available(ctx) {
		data, err := c.Get(ctx, "godemo.bakups")
		if err != nil {
			glog.Info(ctx, "没有配置 godemo.bakups 跳过文件备份!")
		}
		var items []BakupItem
		if err = data.Structs(&items); err != nil {
			glog.Info(ctx, "没有配置 godemo.bakups 跳过文件备份! %v", err)
		}
		for i := range items {
			item := items[i]
			glog.Infof(ctx, "开始备份文件 [%s] 到 [%s] ", item.Source, item.To)
			list, _ := gfile.ScanDirFunc(item.Source, "*", true, func(path string) string {
				// 防止递归备份
				if gstr.Contains(path, item.To) {
					return ""
				}
				if gstr.HasSuffix(path, "docx") {
					return path
				}
				return ""
			})
			glog.Info(ctx, "扫描到文件数量: ", len(list))
			for _, v := range list {
				glog.Info(ctx, "备份文件: ", v)
				dpath := gstr.Replace(v, item.Source, item.To)
				glog.Info(ctx, "备份文件: ", dpath)
			}
		}
	}
}
